package com.macaku.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macaku.common.SystemJsonResponse;
import com.macaku.domain.po.ShortLink;
import com.macaku.service.ShortLinkService;
import com.macaku.mapper.ShortLinkMapper;
import com.macaku.util.RedisCache;
import com.macaku.util.RedissonBloomFilter;
import com.macaku.util.ShortLinkUtils;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.RedirectView;

import java.util.Date;
import java.util.Objects;

/**
* @author 马拉圈
* @description 针对表【short_link】的数据库操作Service实现
* @createDate 2024-01-12 19:48:07
*/
@Service
@RequiredArgsConstructor
public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper, ShortLink>
    implements ShortLinkService{


    private final RedisCache redisCache;

    @Override
    public String transShortLinkURL(String baseUrl, String url) {
        //获取短链接code
        ShortLink one = null;
        String code = url;
        String redisKey = null;
        do {
            code = ShortLinkUtils.getShortCodeByURL(code);
            redisKey = ShortLinkUtils.LINK + code;
        } while (RedissonBloomFilter.contains(redisKey));//误判为存在也无所谓，无非就是再重新生成一个
        // 保存
        ShortLink shortLink = new ShortLink();
        shortLink.setOriginUrl(url);
        shortLink.setShortCode(code);
        shortLink.setIsDeleted(false);
        shortLink.setIsUsed(false);
        shortLink.setCreateTime(new Date());
        this.save(shortLink);
        redisCache.setCacheObject(redisKey, url);
        RedissonBloomFilter.add(redisKey);
        return baseUrl + code;
    }

    @Override
    public String getOriginUrl(String code) {
        String redisKey = ShortLinkUtils.LINK + code;
        String originUrl = redisCache.getCacheObject(redisKey);
        if(Objects.nonNull(originUrl)) {
            return originUrl;
        }
        ShortLink shortLink = this.lambdaQuery().eq(ShortLink::getShortCode, code).one();
        if(Objects.isNull(shortLink)) {
            log.warn("不存在此短链接code：" + code);
            throw new RuntimeException("不存在此短链接");
        }
        redisCache.setCacheObject(redisKey, shortLink.getOriginUrl());
        return shortLink.getOriginUrl();
    }


}




